package edu.chalmers.targine;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

public class ServerConnection {
	private final String SERVER = "129.16.157.71";
	private final int PORT = 1337;
	
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	
//	private String value = null;
	private String[] message = new String[3];
	private boolean communicate = false;
	
	protected List<ServerConnectionEventListener> listenerList = new ArrayList<ServerConnectionEventListener>();
	
	public void startCommunicatingWithServer(){
		new Thread(){
			@Override
			public void run(){
				try {
					socket = new Socket(SERVER, PORT);
					in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
					communicate = true;
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				String readLine = null;
				try {
					while(communicate && (readLine = in.readLine()) != null){
						if(!readLine.equals("none")){
							String key = readLine.substring(0, readLine.indexOf(':'));
							String value = readLine.substring(readLine.indexOf(":") + 1);
							message[0] = key.substring(0, key.indexOf('.'));
							message[1] = key.substring(key.indexOf('.') + 1);
							message[2] = value;
							setMessage(message);
						}
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	public synchronized void stopCommunicatingWithServer(){
		communicate = false;
	}
	
	public void setSharedData(String key, String value){
		if(out != null){
			Log.d("ServerConnection", "Sending " + value);
			out.println(key + ":" + value);
		}
	}
	
	public void sendCommandToServer(String command){
		if(out != null){
			Log.d("ServerConnection", "Sending command: " + command);
			out.println(command);
		}
	}
	
	private synchronized void setMessage(String[] newMessage){
		message = newMessage;
		fireEvent();
	}
	
	protected synchronized String[] getMessage(){
		return message;
	}
	
	public synchronized void addEventListener(ServerConnectionEventListener listener){
		listenerList.add(listener);
	}
	
	public synchronized void removeEventListener(ServerConnectionEventListener listener){
		listenerList.remove(listener);
	}
	
	private synchronized void fireEvent(){
		for(ServerConnectionEventListener l : listenerList){
			l.serverConnectionEventOccurred(message);
		}
	}
}
